package sbc.ms;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.xvsm.api.core.Capi;
import org.xvsm.api.core.ContainerRef;
import org.xvsm.api.core.CoordinationTypes;
import org.xvsm.api.core.Entry;
import org.xvsm.api.core.Tuple;
import org.xvsm.api.core.ValueTypes;
import org.xvsm.client.ClientCapi;

import sbc.model.*;

public class Producer extends Thread {

	private Capi capi;
	private Platine platine;
	private Sensor sensor;

	public Producer(String url, Platine platine) {
		try {
			Logger.getLogger("org.xvsm.client").setLevel(Level.WARN);
			this.capi = new ClientCapi(url);
			capi.init(false);
			this.platine = platine;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Producer(String url, Sensor sensor) {
		try {
			Logger.getLogger("org.xvsm.client").setLevel(Level.WARN);
			this.capi = new ClientCapi(url);
			capi.init(false);
			this.sensor = sensor;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			ContainerRef cref = Util.getOrCreateNamedContainer(capi,
					"Container", CoordinationTypes.FIFO);

			System.out.println("CREF: " + cref);

			if (platine != null) {
				Entry d1 = Entry.Factory.newInstance(ValueTypes.STRING_UTF8, "Platine");
				Entry d2 = Entry.Factory.newInstance(ValueTypes.STRING_UTF8, platine.getMyId());
				Tuple t = new Tuple();
				t.addEntry(d1);
				t.addEntry(d2);
				List<Entry> entryList = new LinkedList<Entry>();
				entryList.add(t);
				capi.write(cref, entryList);
				System.out.println("Platine: " + entryList + " written");
			}
			if (sensor != null) {
				Entry d1 = Entry.Factory.newInstance(ValueTypes.STRING_UTF8, "Sensor");
				Entry d2 = Entry.Factory.newInstance(ValueTypes.STRING_UTF8, sensor.getMyId());
				Tuple t = new Tuple();
				t.addEntry(d1);
				t.addEntry(d2);
				List<Entry> entryList = new LinkedList<Entry>();
				entryList.add(t);
				capi.write(cref, entryList);
				System.out.println("Sensor: " + entryList + " written");
			}
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}
